package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {


    //注入mongdb服务
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async //开启异步调用 --还有启动类
    public void insert(String keyword, Integer userId) {
        //根据关键词查询mongdb中是否有该关键词的记录
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //若关键词存在就更新关键词的时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            //更新时间后调添加就可覆盖原来的数据
            mongoTemplate.save(apUserSearch);
        }

        //不存在的话,判断目前关键词历史总数是否超过十条,超过就更新换掉创建时间最早的一条
        apUserSearch = new ApUserSearch();
        //封装数据
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        //判断是否小于10条,小于就直接插入更新,大于就更新换掉时间最久的一条数据
        if (apUserSearchList != null  && apUserSearchList.size() <10) {
            mongoTemplate.save(apUserSearch);
        }else {
            //大于10条 长度减一 然后将新的这条数据更新上去
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),apUserSearch);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获取用户
        ApUser user = AppThreadLocalUtil.getUser();
        List<ApUserSearch> list = new ArrayList<>(0);
        //非空
        if (user !=null) {
            Query query = Query.query(Criteria.where("userId")
                    .is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
             list = mongoTemplate.find(query,ApUserSearch.class);
        }

        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //检查参数
        if (null != dto && StringUtils.isNotEmpty(dto.getId())) {
            //判断是否登录
            ApUser user = AppThreadLocalUtil.getUser();
            if (null != user){
                //删除
                mongoTemplate.remove(Query.query(Criteria.where("id")
                        .is(dto.getId())
                        .and("userId")
                        .is(user.getId()))
                        ,ApUserSearch.class);

            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
